<template>
  <div class="finance-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h1>财务管理</h1>
          <p>管理您的资金和提现，查看收入统计和交易记录</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showWithdrawDialog" :disabled="!canWithdraw">
            <el-icon><Wallet /></el-icon>
            申请提现
          </el-button>
          <el-button @click="showFinanceAnalysis">
            <el-icon><TrendCharts /></el-icon>
            财务分析
          </el-button>
          <el-button @click="handleExportTransactions">
            <el-icon><Download /></el-icon>
            导出记录
          </el-button>
        </div>
      </div>
    </div>

    <!-- 资金概览 -->
    <el-row :gutter="20" class="finance-overview">
      <el-col :span="8">
        <el-card shadow="hover" class="balance-card available">
          <div class="balance-content">
            <div class="balance-icon">
              <el-icon><Wallet /></el-icon>
            </div>
            <div class="balance-info">
              <div class="balance-amount">¥{{ formatMoney(financeData.availableBalance) }}</div>
              <div class="balance-label">可提现余额</div>
              <div class="balance-desc">已完成订单的资金，可以申请提现</div>
              <div class="balance-action">
                <el-button
                  type="primary"
                  size="small"
                  @click="showWithdrawDialog"
                  :disabled="financeData.availableBalance < 100"
                >
                  申请提现
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="balance-card frozen">
          <div class="balance-content">
            <div class="balance-icon">
              <el-icon><Lock /></el-icon>
            </div>
            <div class="balance-info">
              <div class="balance-amount">¥{{ formatMoney(financeData.frozenBalance) }}</div>
              <div class="balance-label">冻结金额</div>
              <div class="balance-desc">因风控或投诉冻结的资金，需要处理后解冻</div>
              <div class="balance-action" v-if="financeData.frozenBalance > 0">
                <el-button size="small" type="warning" @click="viewFrozenDetails">
                  查看详情
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" class="balance-card pending">
          <div class="balance-content">
            <div class="balance-icon">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="balance-info">
              <div class="balance-amount">¥{{ formatMoney(financeData.pendingBalance) }}</div>
              <div class="balance-label">在途金额</div>
              <div class="balance-desc">14天结算期内的资金，到期后转为可提现</div>
              <div class="balance-action">
                <el-button size="small" @click="viewPendingDetails">
                  查看明细
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 提现规则说明 -->
    <el-card class="rules-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>提现规则</span>
          <el-tag type="info">重要说明</el-tag>
        </div>
      </template>
      <div class="rules-content">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="rule-item">
              <div class="rule-icon">
                <el-icon><Money /></el-icon>
              </div>
              <div class="rule-info">
                <div class="rule-title">最低提现金额</div>
                <div class="rule-desc">100元</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="rule-item">
              <div class="rule-icon">
                <el-icon><CreditCard /></el-icon>
              </div>
              <div class="rule-info">
                <div class="rule-title">提现手续费</div>
                <div class="rule-desc">免费</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="rule-item">
              <div class="rule-icon">
                <el-icon><Timer /></el-icon>
              </div>
              <div class="rule-info">
                <div class="rule-title">到账时间</div>
                <div class="rule-desc">1-3个工作日</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="rule-item">
              <div class="rule-icon">
                <el-icon><Wallet /></el-icon>
              </div>
              <div class="rule-info">
                <div class="rule-title">支持方式</div>
                <div class="rule-desc">银行卡、支付宝、微信</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 收入统计 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="12">
        <el-card shadow="hover" class="income-card">
          <template #header>
            <div class="card-header">
              <span>收入统计</span>
              <el-select v-model="incomeTimeRange" size="small" style="width: 120px;">
                <el-option label="本周" value="week" />
                <el-option label="本月" value="month" />
                <el-option label="本季度" value="quarter" />
                <el-option label="本年" value="year" />
              </el-select>
            </div>
          </template>
          <div class="income-stats">
            <div class="income-item">
              <span class="income-label">总收入</span>
              <span class="income-value total">¥{{ formatMoney(incomeStats.total) }}</span>
            </div>
            <div class="income-item">
              <span class="income-label">订单数量</span>
              <span class="income-value orders">{{ incomeStats.orderCount }}单</span>
            </div>
            <div class="income-item">
              <span class="income-label">平均客单价</span>
              <span class="income-value avg">¥{{ formatMoney(incomeStats.avgOrderAmount) }}</span>
            </div>
            <div class="income-item">
              <span class="income-label">增长率</span>
              <span class="income-value growth" :class="incomeStats.growthRate >= 0 ? 'positive' : 'negative'">
                {{ incomeStats.growthRate >= 0 ? '+' : '' }}{{ incomeStats.growthRate }}%
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card shadow="hover" class="risk-card">
          <template #header>
            <div class="card-header">
              <span>风控状态</span>
              <el-tag :type="getRiskLevelType()" size="small">
                {{ getRiskLevelText() }}
              </el-tag>
            </div>
          </template>
          <div class="risk-content">
            <div class="risk-item">
              <span class="risk-label">信用分数</span>
              <div class="risk-score">
                <el-progress
                  :percentage="financeData.creditScore"
                  :color="getCreditScoreColor(financeData.creditScore)"
                  :show-text="false"
                />
                <span class="score-text">{{ financeData.creditScore }}分</span>
              </div>
              <div class="risk-tip">影响平台推荐权重</div>
            </div>
            <div class="risk-item">
              <span class="risk-label">好评率</span>
              <span class="risk-value" :class="getRiskClass('goodReview', financeData.goodReviewRate)">
                {{ financeData.goodReviewRate }}%
              </span>
              <div class="risk-tip">
                {{ getRiskTip('goodReview', financeData.goodReviewRate) }}
              </div>
            </div>
            <div class="risk-item">
              <span class="risk-label">退款率</span>
              <span class="risk-value" :class="getRiskClass('refund', financeData.refundRate)">
                {{ financeData.refundRate }}%
              </span>
              <div class="risk-tip">
                {{ getRiskTip('refund', financeData.refundRate) }}
              </div>
            </div>
            <div class="risk-item">
              <span class="risk-label">完成率</span>
              <span class="risk-value">{{ financeData.completionRate }}%</span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 风控机制说明 -->
    <el-card class="risk-rules-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>风控机制</span>
          <el-tag type="warning">重要提醒</el-tag>
        </div>
      </template>
      <div class="risk-rules-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="risk-rule-section">
              <h4>提现限制</h4>
              <ul class="risk-rule-list">
                <li>
                  <span class="rule-condition">退款率 > 15%</span>
                  <span class="rule-result">需要人工审核提现</span>
                </li>
                <li>
                  <span class="rule-condition">好评率 < 70%</span>
                  <span class="rule-result">限制自动提现</span>
                </li>
              </ul>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="risk-rule-section">
              <h4>搜索排名影响</h4>
              <ul class="risk-rule-list">
                <li>
                  <span class="rule-condition">好评率 < 80%</span>
                  <span class="rule-result">影响搜索排名</span>
                </li>
                <li>
                  <span class="rule-condition">信用分数</span>
                  <span class="rule-result">影响平台推荐权重</span>
                </li>
              </ul>
            </div>
          </el-col>
        </el-row>

        <div class="settlement-info">
          <h4>结算周期</h4>
          <p>为保障服务质量，平台采用14天结算周期。订单完成后，资金将在14天后自动转入可提现余额。</p>
        </div>
      </div>
    </el-card>

    <!-- 交易记录 -->
    <el-card shadow="hover" class="transaction-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>交易记录</span>
          <div class="header-actions">
            <el-select v-model="transactionType" placeholder="交易类型" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="all" />
              <el-option label="收入" value="income" />
              <el-option label="提现" value="withdraw" />
              <el-option label="冻结" value="freeze" />
              <el-option label="解冻" value="unfreeze" />
            </el-select>
            <el-button type="primary" @click="handleExportTransactions">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table :data="filteredTransactions" style="width: 100%" v-loading="transactionLoading">
        <el-table-column prop="transactionId" label="交易号" width="160" />
        <el-table-column label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTransactionTypeColor(scope.row.type)">
              {{ getTransactionTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="金额" width="120">
          <template #default="scope">
            <span :class="scope.row.type === 'income' ? 'amount-positive' : 'amount-negative'">
              {{ scope.row.type === 'income' ? '+' : '-' }}¥{{ formatMoney(scope.row.amount) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusTypeColor(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="时间" width="160" />
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button size="small" @click="viewTransactionDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalTransactions"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 提现对话框 -->
    <el-dialog
      v-model="withdrawDialogVisible"
      title="申请提现"
      width="500px"
      @close="resetWithdrawForm"
    >
      <el-form
        ref="withdrawFormRef"
        :model="withdrawForm"
        :rules="withdrawRules"
        label-width="100px"
      >
        <el-form-item label="提现金额" prop="amount">
          <el-input-number
            v-model="withdrawForm.amount"
            :min="100"
            :max="financeData.availableBalance"
            :precision="2"
            controls-position="right"
            style="width: 100%;"
            placeholder="请输入提现金额"
          />
          <div class="form-tips">
            <div class="form-tip">
              可提现余额：¥{{ formatMoney(financeData.availableBalance) }}
            </div>
            <div class="form-tip">
              最低提现金额：¥100
            </div>
            <div class="form-tip">
              提现手续费：免费
            </div>
          </div>
        </el-form-item>
        <el-form-item label="提现方式" prop="method">
          <el-radio-group v-model="withdrawForm.method" @change="handleMethodChange">
            <el-radio label="bank">银行卡</el-radio>
            <el-radio label="alipay">支付宝</el-radio>
            <el-radio label="wechat">微信</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 银行卡选择 -->
        <el-form-item v-if="withdrawForm.method === 'bank'" label="选择银行卡" prop="bankCardId">
          <div class="bank-card-selection">
            <el-select
              v-model="withdrawForm.bankCardId"
              placeholder="选择银行卡"
              style="width: 100%;"
              @change="handleBankCardChange"
            >
              <el-option
                v-for="card in bankCards"
                :key="card.id"
                :label="`${card.bankName} (****${card.cardNumber.slice(-4)})`"
                :value="card.id"
              />
            </el-select>
            <el-button
              type="primary"
              link
              @click="showAddBankCardDialog"
              style="margin-top: 8px;"
            >
              + 添加新银行卡
            </el-button>
          </div>
        </el-form-item>

        <!-- 其他支付方式账户信息 -->
        <el-form-item v-else label="账户信息" prop="account">
          <el-input
            v-model="withdrawForm.account"
            :placeholder="getAccountPlaceholder()"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="withdrawForm.remark"
            type="textarea"
            placeholder="请输入备注（选填）"
            :rows="3"
          />
        </el-form-item>
        <el-alert
          v-if="needManualReview"
          title="风控提醒"
          type="warning"
          description="由于您的退款率或好评率异常，本次提现需要人工审核，预计1-3个工作日到账"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;"
        />
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="withdrawDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="withdrawSubmitting" @click="submitWithdraw">
            确认提现
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加银行卡对话框 -->
    <el-dialog
      v-model="addBankCardDialogVisible"
      title="添加银行卡"
      width="500px"
      @close="resetBankCardForm"
    >
      <el-form
        ref="bankCardFormRef"
        :model="bankCardForm"
        :rules="bankCardRules"
        label-width="100px"
      >
        <el-form-item label="持卡人姓名" prop="holderName">
          <el-input
            v-model="bankCardForm.holderName"
            placeholder="请输入持卡人姓名"
          />
        </el-form-item>
        <el-form-item label="银行卡号" prop="cardNumber">
          <el-input
            v-model="bankCardForm.cardNumber"
            placeholder="请输入银行卡号"
            maxlength="19"
            @input="formatCardNumber"
          />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName">
          <el-select v-model="bankCardForm.bankName" placeholder="请选择开户银行" style="width: 100%;">
            <el-option label="中国工商银行" value="ICBC" />
            <el-option label="中国建设银行" value="CCB" />
            <el-option label="中国农业银行" value="ABC" />
            <el-option label="中国银行" value="BOC" />
            <el-option label="招商银行" value="CMB" />
            <el-option label="交通银行" value="BOCOM" />
            <el-option label="中信银行" value="CITIC" />
            <el-option label="光大银行" value="CEB" />
            <el-option label="华夏银行" value="HXB" />
            <el-option label="民生银行" value="CMBC" />
            <el-option label="广发银行" value="CGB" />
            <el-option label="平安银行" value="PAB" />
            <el-option label="浦发银行" value="SPDB" />
            <el-option label="兴业银行" value="CIB" />
          </el-select>
        </el-form-item>
        <el-form-item label="开户支行" prop="branchName">
          <el-input
            v-model="bankCardForm.branchName"
            placeholder="请输入开户支行"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input
            v-model="bankCardForm.phone"
            placeholder="请输入预留手机号"
            maxlength="11"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addBankCardDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="bankCardSubmitting" @click="submitBankCard">
            确认添加
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 财务分析对话框 -->
    <el-dialog
      v-model="analysisDialogVisible"
      title="财务分析报告"
      width="800px"
      top="5vh"
    >
      <div v-if="analysisData" class="analysis-content">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="analysis-card">
              <template #header>
                <span>收入趋势</span>
              </template>
              <div class="trend-chart">
                <!-- 这里可以集成图表库如ECharts -->
                <div class="chart-placeholder">
                  <p>收入趋势图表</p>
                  <p>本月收入：¥{{ formatMoney(analysisData.monthlyIncome) }}</p>
                  <p>环比增长：{{ analysisData.incomeGrowth }}%</p>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="analysis-card">
              <template #header>
                <span>支出分析</span>
              </template>
              <div class="expense-analysis">
                <div class="expense-item">
                  <span>平台服务费：</span>
                  <span>¥{{ formatMoney(analysisData.platformFee) }}</span>
                </div>
                <div class="expense-item">
                  <span>提现手续费：</span>
                  <span>¥{{ formatMoney(analysisData.withdrawFee) }}</span>
                </div>
                <div class="expense-item">
                  <span>其他费用：</span>
                  <span>¥{{ formatMoney(analysisData.otherFee) }}</span>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="analysis-card" style="margin-top: 20px;">
          <template #header>
            <span>经营建议</span>
          </template>
          <div class="suggestions">
            <ul>
              <li v-for="suggestion in analysisData.suggestions" :key="suggestion">
                {{ suggestion }}
              </li>
            </ul>
          </div>
        </el-card>
      </div>

      <template #footer>
        <el-button @click="analysisDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="exportAnalysisReport">导出报告</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Wallet,
  Lock,
  Clock,
  Download,
  Money,
  CreditCard,
  Timer,
  TrendCharts
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getFinanceOverview,
  getIncomeList,
  getExpenseList,
  getAccountBalance,
  getBalanceInfo,
  getRiskStatus,
  applyWithdraw,
  getWithdrawList,
  getTransactionList,
  getTransactionDetail,
  exportTransactions,
  getRiskInfo,
  getFrozenDetails,
  getPendingDetails,
  getIncomeStats,
  getFinanceAnalysis,
  getBankCardList,
  addBankCard,
  setDefaultBankCard,
  validateWithdraw,
  getWithdrawRules,
  TRANSACTION_TYPES,
  TRANSACTION_STATUS,
  WITHDRAW_METHODS,
  TRANSACTION_TYPE_TEXT,
  TRANSACTION_STATUS_TEXT,
  WITHDRAW_METHOD_TEXT,
  TRANSACTION_TYPE_COLOR,
  TRANSACTION_STATUS_COLOR,
  RISK_LEVELS,
  RISK_LEVEL_TEXT,
  RISK_LEVEL_COLOR
} from '@/api/finance'

const userStore = useUserStore()

// 响应式数据
const transactionLoading = ref(false)
const incomeTimeRange = ref('month')
const transactionType = ref('all')
const currentPage = ref(1)
const pageSize = ref(20)
const totalTransactions = ref(0)

// 财务数据
const financeData = reactive({
  availableBalance: 0,
  frozenBalance: 0,
  pendingBalance: 0,
  creditScore: 0,
  goodReviewRate: 0,
  refundRate: 0,
  completionRate: 0
})

// 收入统计
const incomeStats = reactive({
  total: 0,
  orderCount: 0,
  avgOrderAmount: 0,
  growthRate: 0
})

// 交易记录
const transactions = ref([])

// 提现对话框
const withdrawDialogVisible = ref(false)
const withdrawSubmitting = ref(false)
const withdrawFormRef = ref()
const withdrawForm = reactive({
  amount: '',
  method: 'bank',
  account: '',
  remark: ''
})

// 提现表单验证规则
const withdrawRules = {
  amount: [
    { required: true, message: '请输入提现金额', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value || value <= 0) {
          callback(new Error('提现金额必须大于0'))
        } else if (value < 100) {
          callback(new Error('最低提现金额为100元'))
        } else if (value > financeData.availableBalance) {
          callback(new Error('提现金额不能超过可提现余额'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  method: [
    { required: true, message: '请选择提现方式', trigger: 'change' }
  ],
  bankCardId: [
    { required: true, message: '请选择银行卡', trigger: 'change' }
  ],
  account: [
    { required: true, message: '请输入账户信息', trigger: 'blur' }
  ]
}

// 银行卡管理相关
const addBankCardDialogVisible = ref(false)
const bankCardSubmitting = ref(false)
const bankCardFormRef = ref()
const bankCards = ref([])
const bankCardForm = reactive({
  holderName: '',
  cardNumber: '',
  bankName: '',
  branchName: '',
  phone: ''
})

// 银行卡表单验证规则
const bankCardRules = {
  holderName: [
    { required: true, message: '请输入持卡人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  cardNumber: [
    { required: true, message: '请输入银行卡号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        const cleanValue = value.replace(/\s/g, '')
        if (!/^\d{16,19}$/.test(cleanValue)) {
          callback(new Error('请输入正确的银行卡号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  bankName: [
    { required: true, message: '请选择开户银行', trigger: 'change' }
  ],
  branchName: [
    { required: true, message: '请输入开户支行', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 财务分析相关
const analysisDialogVisible = ref(false)
const analysisData = ref(null)

// 计算属性
const filteredTransactions = computed(() => {
  if (transactionType.value === 'all') {
    return transactions.value
  }
  return transactions.value.filter(t => t.type === transactionType.value)
})

const needManualReview = computed(() => {
  return financeData.refundRate > 15 || financeData.goodReviewRate < 70
})

const canWithdraw = computed(() => {
  return financeData.availableBalance >= 100 && financeData.goodReviewRate >= 70
})

// 获取财务数据
const getFinanceData = async () => {
  try {
    // 获取余额信息
    const balanceResponse = await getBalanceInfo()
    if (balanceResponse.code === 200) {
      const balanceData = balanceResponse.data
      financeData.availableBalance = balanceData.availableBalance || 0
      financeData.frozenBalance = balanceData.frozenBalance || 0
      financeData.pendingBalance = balanceData.pendingBalance || 0
    }

    // 获取风控状态
    const riskResponse = await getRiskStatus()
    if (riskResponse.code === 200) {
      const riskData = riskResponse.data
      financeData.creditScore = riskData.creditScore || 0
      financeData.goodReviewRate = riskData.goodReviewRate || 0
      financeData.refundRate = riskData.refundRate || 0
      financeData.completionRate = riskData.completionRate || 0
    }
  } catch (error) {
    console.error('获取财务数据失败:', error)
    ElMessage.error(error.message || '获取财务数据失败')
  }
}

// 获取收入统计
const getIncomeStatsData = async () => {
  try {
    const response = await getIncomeStats(incomeTimeRange.value)
    if (response.code === 200) {
      const data = response.data
      incomeStats.total = data.total || 0
      incomeStats.orderCount = data.orderCount || 0
      incomeStats.avgOrderAmount = data.avgOrderAmount || 0
      incomeStats.growthRate = data.growthRate || 0
    } else {
      throw new Error(response.message || '获取收入统计失败')
    }
  } catch (error) {
    console.error('获取收入统计失败:', error)
    ElMessage.error(error.message || '获取收入统计失败')
  }
}

// 获取交易记录
const getTransactionData = async () => {
  try {
    transactionLoading.value = true
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      type: transactionType.value !== 'all' ? transactionType.value : undefined
    }

    const response = await getTransactionList(params)
    if (response.code === 200) {
      transactions.value = response.data.records || response.data || []
      totalTransactions.value = response.data.total || transactions.value.length
    } else {
      throw new Error(response.message || '获取交易记录失败')
    }
  } catch (error) {
    console.error('获取交易记录失败:', error)
    ElMessage.error(error.message || '获取交易记录失败')
    transactions.value = []
    totalTransactions.value = 0
  } finally {
    transactionLoading.value = false
  }
}

// 方法
const formatMoney = (amount) => {
  return (amount || 0).toLocaleString()
}

const getRiskLevelType = () => {
  if (financeData.creditScore >= 90) return 'success'
  if (financeData.creditScore >= 80) return 'primary'
  if (financeData.creditScore >= 70) return 'warning'
  return 'danger'
}

const getRiskLevelText = () => {
  if (financeData.creditScore >= 90) return '优秀'
  if (financeData.creditScore >= 80) return '良好'
  if (financeData.creditScore >= 70) return '一般'
  return '较差'
}

const getCreditScoreColor = (score) => {
  if (score >= 90) return '#67c23a'
  if (score >= 80) return '#409eff'
  if (score >= 70) return '#e6a23c'
  return '#f56c6c'
}

const getTransactionTypeColor = (type) => {
  return TRANSACTION_TYPE_COLOR[type] || 'info'
}

const getTransactionTypeText = (type) => {
  return TRANSACTION_TYPE_TEXT[type] || type
}

const getStatusTypeColor = (status) => {
  return TRANSACTION_STATUS_COLOR[status] || 'info'
}

const getStatusText = (status) => {
  return TRANSACTION_STATUS_TEXT[status] || status
}

// 获取风控等级样式
const getRiskClass = (type, value) => {
  if (type === 'goodReview') {
    if (value < 70) return 'high-risk'
    if (value < 80) return 'medium-risk'
    return 'low-risk'
  } else if (type === 'refund') {
    if (value > 15) return 'high-risk'
    if (value > 10) return 'medium-risk'
    return 'low-risk'
  }
  return ''
}

// 获取风控提示
const getRiskTip = (type, value) => {
  if (type === 'goodReview') {
    if (value < 70) return '限制自动提现'
    if (value < 80) return '影响搜索排名'
    return '表现良好'
  } else if (type === 'refund') {
    if (value > 15) return '需要人工审核提现'
    if (value > 10) return '接近风控阈值'
    return '表现良好'
  }
  return ''
}

// 查看冻结详情
const viewFrozenDetails = async () => {
  try {
    const response = await getFrozenDetails()
    if (response.code === 200) {
      const details = response.data
      let content = '冻结资金详情：\n\n'

      if (details && details.length > 0) {
        details.forEach(item => {
          content += `• 冻结原因：${item.reason}\n`
          content += `• 冻结金额：¥${formatMoney(item.amount)}\n`
          content += `• 冻结时间：${item.freezeTime}\n`
          content += `• 预计解冻：${item.expectedUnfreezeTime || '处理中'}\n\n`
        })
      } else {
        content += '暂无冻结资金'
      }

      ElMessageBox.alert(content, '冻结资金详情', {
        confirmButtonText: '确定'
      })
    } else {
      throw new Error(response.message || '获取冻结详情失败')
    }
  } catch (error) {
    console.error('获取冻结详情失败:', error)
    ElMessage.error(error.message || '获取冻结详情失败')
  }
}

// 查看在途资金详情
const viewPendingDetails = async () => {
  try {
    const response = await getPendingDetails()
    if (response.code === 200) {
      const details = response.data
      let content = '在途资金明细：\n\n'

      if (details && details.length > 0) {
        details.forEach(item => {
          const remainingDays = Math.ceil((new Date(item.settlementTime) - new Date()) / (1000 * 60 * 60 * 24))
          content += `• 订单${item.orderNo}：¥${formatMoney(item.amount)}（剩余${remainingDays}天）\n`
        })
        content += '\n这些资金将在14天结算期满后自动转入可提现余额'
      } else {
        content += '暂无在途资金'
      }

      ElMessageBox.alert(content, '在途资金详情', {
        confirmButtonText: '确定'
      })
    } else {
      throw new Error(response.message || '获取在途资金详情失败')
    }
  } catch (error) {
    console.error('获取在途资金详情失败:', error)
    ElMessage.error(error.message || '获取在途资金详情失败')
  }
}

// 显示提现对话框
const showWithdrawDialog = async () => {
  try {
    // 验证提现条件
    const validateResponse = await validateWithdraw(100)
    if (validateResponse.code !== 200) {
      ElMessage.warning(validateResponse.message || '当前无法申请提现')
      return
    }

    if (financeData.availableBalance < 100) {
      ElMessage.warning('可提现余额不足100元，无法申请提现')
      return
    }

    if (financeData.goodReviewRate < 70) {
      ElMessage.warning('好评率低于70%，暂时限制提现功能')
      return
    }

    // 加载银行卡列表
    await loadBankCardList()

    withdrawDialogVisible.value = true
  } catch (error) {
    console.error('验证提现条件失败:', error)
    ElMessage.error(error.message || '验证提现条件失败')
  }
}

// 重置提现表单
const resetWithdrawForm = () => {
  if (withdrawFormRef.value) {
    withdrawFormRef.value.resetFields()
  }
  withdrawForm.amount = ''
  withdrawForm.method = 'bank'
  withdrawForm.account = ''
  withdrawForm.remark = ''
}

// 提交提现申请
const submitWithdraw = async () => {
  if (!withdrawFormRef.value) return

  await withdrawFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        withdrawSubmitting.value = true

        // 再次验证提现条件
        const validateResponse = await validateWithdraw(withdrawForm.amount)
        if (validateResponse.code !== 200) {
          ElMessage.warning(validateResponse.message || '提现条件验证失败')
          return
        }

        const withdrawData = {
          amount: withdrawForm.amount,
          method: withdrawForm.method,
          bankCardId: withdrawForm.method === 'bank' ? withdrawForm.bankCardId : undefined,
          account: withdrawForm.method !== 'bank' ? withdrawForm.account : undefined,
          remark: withdrawForm.remark
        }

        const response = await applyWithdraw(withdrawData)

        if (response.code === 200) {
          ElMessage.success(needManualReview.value ? '提现申请已提交，请等待人工审核' : '提现申请已提交，预计1-3个工作日到账')
          withdrawDialogVisible.value = false
          resetWithdrawForm()

          // 刷新财务数据
          await getFinanceData()
          await getTransactionData()
        } else {
          throw new Error(response.message || '提现申请失败')
        }
      } catch (error) {
        console.error('提现申请失败:', error)
        ElMessage.error(error.message || '提现申请失败')
      } finally {
        withdrawSubmitting.value = false
      }
    }
  })
}

// 查看交易详情
const viewTransactionDetail = async (transaction) => {
  try {
    const response = await getTransactionDetail(transaction.transactionId || transaction.id)
    if (response.code === 200) {
      const detail = response.data
      let content = `交易号：${detail.transactionId}\n`
      content += `类型：${getTransactionTypeText(detail.type)}\n`
      content += `金额：¥${formatMoney(detail.amount)}\n`
      content += `描述：${detail.description}\n`
      content += `状态：${getStatusText(detail.status)}\n`
      content += `时间：${detail.createTime}\n`

      if (detail.remark) {
        content += `备注：${detail.remark}\n`
      }

      if (detail.relatedOrderNo) {
        content += `关联订单：${detail.relatedOrderNo}\n`
      }

      ElMessageBox.alert(content, '交易详情', {
        confirmButtonText: '确定'
      })
    } else {
      throw new Error(response.message || '获取交易详情失败')
    }
  } catch (error) {
    console.error('获取交易详情失败:', error)
    // 使用基本信息作为备用
    ElMessageBox.alert(
      `交易号：${transaction.transactionId}\n类型：${getTransactionTypeText(transaction.type)}\n金额：¥${formatMoney(transaction.amount)}\n描述：${transaction.description}\n状态：${getStatusText(transaction.status)}\n时间：${transaction.createTime}`,
      '交易详情',
      {
        confirmButtonText: '确定'
      }
    )
  }
}

// 导出交易记录
const handleExportTransactions = async () => {
  try {
    const params = {
      type: transactionType.value !== 'all' ? transactionType.value : undefined,
      startDate: '',
      endDate: ''
    }

    const response = await exportTransactions(params)

    if (response instanceof Blob) {
      const url = URL.createObjectURL(response)
      const link = document.createElement('a')
      link.href = url
      link.download = `交易记录_${new Date().toISOString().slice(0, 10)}.xlsx`
      link.click()
      URL.revokeObjectURL(url)
      ElMessage.success('交易记录导出成功')
    } else {
      throw new Error('导出失败')
    }
  } catch (error) {
    console.error('导出交易记录失败:', error)
    ElMessage.error(error.message || '导出交易记录失败')
  }
}

// 财务分析方法
const showFinanceAnalysis = async () => {
  try {
    const response = await getFinanceAnalysis({
      timeRange: incomeTimeRange.value
    })

    if (response.code === 200) {
      analysisData.value = response.data
      analysisDialogVisible.value = true
    } else {
      throw new Error(response.message || '获取分析数据失败')
    }
  } catch (error) {
    console.error('获取财务分析失败:', error)
    ElMessage.error(error.message || '获取财务分析失败')
  }
}

const exportAnalysisReport = async () => {
  try {
    // 生成分析报告并导出
    const reportData = {
      period: incomeTimeRange.value,
      data: analysisData.value
    }

    // 这里可以调用后端API生成PDF报告
    ElMessage.success('分析报告导出功能开发中...')
  } catch (error) {
    console.error('导出分析报告失败:', error)
    ElMessage.error('导出分析报告失败')
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getTransactionData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getTransactionData()
}

// 银行卡管理方法
const loadBankCardList = async () => {
  try {
    const response = await getBankCardList()
    if (response.code === 200) {
      bankCards.value = response.data || []
    }
  } catch (error) {
    console.error('获取银行卡列表失败:', error)
    bankCards.value = []
  }
}

const showAddBankCardDialog = () => {
  addBankCardDialogVisible.value = true
}

const resetBankCardForm = () => {
  if (bankCardFormRef.value) {
    bankCardFormRef.value.resetFields()
  }
  Object.assign(bankCardForm, {
    holderName: '',
    cardNumber: '',
    bankName: '',
    branchName: '',
    phone: ''
  })
}

const formatCardNumber = () => {
  // 格式化银行卡号，每4位加一个空格
  let value = bankCardForm.cardNumber.replace(/\s/g, '')
  value = value.replace(/(\d{4})(?=\d)/g, '$1 ')
  bankCardForm.cardNumber = value
}

const submitBankCard = async () => {
  if (!bankCardFormRef.value) return

  await bankCardFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        bankCardSubmitting.value = true

        const cardData = {
          holderName: bankCardForm.holderName,
          cardNumber: bankCardForm.cardNumber.replace(/\s/g, ''),
          bankName: bankCardForm.bankName,
          branchName: bankCardForm.branchName,
          phone: bankCardForm.phone
        }

        const response = await addBankCard(cardData)

        if (response.code === 200) {
          ElMessage.success('银行卡添加成功')
          addBankCardDialogVisible.value = false
          resetBankCardForm()
          await loadBankCardList()
        } else {
          throw new Error(response.message || '添加银行卡失败')
        }
      } catch (error) {
        console.error('添加银行卡失败:', error)
        ElMessage.error(error.message || '添加银行卡失败')
      } finally {
        bankCardSubmitting.value = false
      }
    }
  })
}

const handleMethodChange = () => {
  // 清空相关字段
  withdrawForm.account = ''
  withdrawForm.bankCardId = ''
}

const handleBankCardChange = (cardId) => {
  const selectedCard = bankCards.value.find(card => card.id === cardId)
  if (selectedCard) {
    withdrawForm.account = `${selectedCard.bankName} (****${selectedCard.cardNumber.slice(-4)})`
  }
}

const getAccountPlaceholder = () => {
  const placeholders = {
    alipay: '请输入支付宝账号',
    wechat: '请输入微信号'
  }
  return placeholders[withdrawForm.method] || '请输入账户信息'
}

// 监听收入时间范围变化
watch(incomeTimeRange, async () => {
  await getIncomeStatsData()
})

// 监听交易类型变化
watch(transactionType, async () => {
  currentPage.value = 1
  await getTransactionData()
})

// 页面初始化
onMounted(async () => {
  await getFinanceData()
  await getIncomeStatsData()
  await getTransactionData()
  await loadBankCardList()
})
</script>

<style scoped>
.finance-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 页面头部 */
.page-header {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #1f2937;
}

.header-left p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions .el-button {
  border-radius: 8px;
}

/* 提现规则 */
.rules-card {
  border-radius: 12px;
  border: none;
}

.rules-content {
  padding: 10px 0;
}

.rule-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background: #f8fafc;
  border-radius: 8px;
  height: 100%;
}

.rule-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  font-size: 18px;
  color: white;
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.rule-info {
  flex: 1;
}

.rule-title {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 4px;
}

.rule-desc {
  font-size: 13px;
  color: #6b7280;
}

/* 风控规则 */
.risk-rules-card {
  border-radius: 12px;
  border: none;
}

.risk-rules-content {
  padding: 10px 0;
}

.risk-rule-section {
  margin-bottom: 20px;
}

.risk-rule-section h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #1f2937;
}

.risk-rule-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.risk-rule-list li {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 8px;
  background: #f8fafc;
  border-radius: 6px;
  border-left: 3px solid #f59e0b;
}

.rule-condition {
  font-size: 13px;
  color: #374151;
  font-weight: 500;
}

.rule-result {
  font-size: 13px;
  color: #dc2626;
}

.settlement-info {
  margin-top: 20px;
  padding: 15px;
  background: #eff6ff;
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.settlement-info h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #1f2937;
}

.settlement-info p {
  margin: 0;
  font-size: 13px;
  color: #6b7280;
  line-height: 1.5;
}

/* 风控提示 */
.risk-tip {
  font-size: 11px;
  color: #6b7280;
  margin-top: 2px;
}

.risk-value.medium-risk {
  color: #f59e0b;
  font-weight: 500;
}

.risk-value.low-risk {
  color: #059669;
}

/* 表单提示 */
.form-tips {
  margin-top: 8px;
}

.form-tips .form-tip {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 2px;
}

.finance-overview {
  margin-bottom: 20px;
}

.balance-card {
  border-radius: 8px;
  overflow: hidden;
}

.balance-card.available {
  border-left: 4px solid #67c23a;
}

.balance-card.frozen {
  border-left: 4px solid #f56c6c;
}

.balance-card.pending {
  border-left: 4px solid #e6a23c;
}

.balance-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.balance-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
  color: white;
}

.available .balance-icon {
  background: #67c23a;
}

.frozen .balance-icon {
  background: #f56c6c;
}

.pending .balance-icon {
  background: #e6a23c;
}

.balance-info {
  flex: 1;
}

.balance-amount {
  font-size: 24px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 5px;
}

.balance-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.balance-desc {
  font-size: 12px;
  color: #9ca3af;
}

.balance-action {
  margin-top: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.income-stats {
  padding: 10px 0;
}

.income-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
}

.income-item:last-child {
  border-bottom: none;
}

.income-label {
  font-size: 14px;
  color: #6b7280;
}

.income-value {
  font-size: 16px;
  font-weight: bold;
}

.income-value.total {
  color: #059669;
}

.income-value.orders {
  color: #3b82f6;
}

.income-value.avg {
  color: #8b5cf6;
}

.income-value.growth.positive {
  color: #059669;
}

.income-value.growth.negative {
  color: #dc2626;
}

.risk-content {
  padding: 10px 0;
}

.risk-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
}

.risk-item:last-child {
  border-bottom: none;
}

.risk-label {
  font-size: 14px;
  color: #6b7280;
}

.risk-value {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.risk-value.high-risk {
  color: #dc2626;
  font-weight: bold;
}

.risk-score {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
  max-width: 150px;
}

.score-text {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.amount-positive {
  color: #059669;
  font-weight: bold;
}

.amount-negative {
  color: #dc2626;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.form-tip {
  font-size: 12px;
  color: #6b7280;
  margin-top: 5px;
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
}

:deep(.el-progress-bar__outer) {
  background-color: #f3f4f6;
}

/* 银行卡选择样式 */
.bank-card-selection {
  width: 100%;
}

.bank-card-selection .el-select {
  margin-bottom: 8px;
}

/* 财务分析对话框样式 */
.analysis-content {
  max-height: 70vh;
  overflow-y: auto;
}

.analysis-card {
  margin-bottom: 20px;
}

.analysis-card:last-child {
  margin-bottom: 0;
}

.trend-chart {
  padding: 20px 0;
}

.chart-placeholder {
  text-align: center;
  padding: 40px 20px;
  background: #f8fafc;
  border-radius: 8px;
  border: 2px dashed #d1d5db;
}

.chart-placeholder p {
  margin: 8px 0;
  color: #6b7280;
}

.expense-analysis {
  padding: 10px 0;
}

.expense-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f3f4f6;
}

.expense-item:last-child {
  border-bottom: none;
}

.suggestions ul {
  margin: 0;
  padding-left: 20px;
}

.suggestions li {
  margin-bottom: 8px;
  color: #374151;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-actions {
    justify-content: center;
    flex-wrap: wrap;
  }

  .analysis-content .el-row {
    flex-direction: column;
  }

  .analysis-content .el-col {
    width: 100%;
    margin-bottom: 20px;
  }
}
</style>
